<template>
  <div>
    <el-card class="search-card">
      <BasicForm
        ref="formData"
        formItemWidth="120px"
        isScalingBtn
        :defaultExpandStatus="false"
        :formColumns="formItemList"
        :dataSource="formData"
        :handleSearchForm="handleQueryForm"
        @getFormData="getFormData"
      />
    </el-card>
    <el-card class="table-card">
      <basic-table
        showActionCol
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :pagination="pagination"
        :pageSizes="pageSizes"
        :tableHeight="480"
        :actionColWidth="140"
        :actionRender="renderTableBtnAction"
        :selectionChange="handleTableSelection"
        @pageChange="handlePageChange"
        @pageSizeChange="handlePageSizeChange"
      >
        <el-row type="flex" slot="content_context">
          <el-button
            v-show="showBtn('新增')"
            icon="el-icon-plus"
            type="primary"
            size="mini"
            @click="handleAdd"
          >新增</el-button>
          <el-button
            v-show="showBtn('导出')"
            icon="el-icon-download"
            type="primary"
            size="mini"
            :loading="btnLoading.export"
            @click="handleExport"
          >导出</el-button>
          <el-button
            v-show="showBtn('删除')"
            icon="el-icon-delete"
            type="primary"
            size="mini"
            :loading="btnLoading.delete"
            :disabled="isEmptyForSelection()"
            @click="handleBatchDelete"
          >批量删除</el-button>
        </el-row>
      </basic-table>
    </el-card>
    <EditDialog
      :visible.sync="qualificationEdit.visible"
      :uuid="qualificationEdit.uuid"
      :isView="qualificationEdit.isView"
    />
  </div>
</template>
<script>
import { getBtnsId } from '@/libs/btnsPermission';
import { mapGetters } from 'vuex';
import BasicForm from '@/components/BasicForm';
import BasicTable from '@/components/BasicTable';
import BasicDialog from '@/components/BasicDialog';
import { requestToData, requestToStatus, requestToExport } from '@/api/commonHttp';
import { formItemList, tableColumns } from './constants';
import { createExcelByExport } from '@/utils/bizUtils';
import { getTableAction } from '@/utils/getBtnsRender';
import EditDialog from './qualificationsManageEdit';
import { getListByReturnMapKey } from '@/utils/getUtils';
export default {
  components: {
    BasicForm,
    BasicTable,
    BasicDialog,
    EditDialog
  },
  data () {
    return {
      formItemList: formItemList,
      formData: {
        qualificationName: '', // 资质名称
        supplyName: '', // 供应商名称
        supplyNo: '', // 供应商编码
        supplierManageAreaName: '', // 供应商管理区域
        purchaseAttributionName: '', // 归属中心
        createOpeTime: [], // 创建时间（包含开始和结束）
        opeTime: [], // 更新时间（包含开始和结束）
        expireDateStart: '', // 过期时间-开始
        expireDateEnd: '', // 过期时间-结束
      },
      tableInfo: {
        list: [],
        columns: tableColumns,
        loading: false,
        selection: []
      },
      pagination: {
        nowPage: 1,
        totalNum: 0,
        pageShow: 10
      },
      pageSizes: [10, 20, 30, 40],
      btnLoading: {
        export: false,
        delete: false
      },
      qualificationEdit: {
        visible: false,
        uuid: '',
        isView: false
      }
    }
  },
  mounted () {
    this.loadInitDataInMounted();
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
  },
  methods: {
    // 表格勾选为空
    isEmptyForSelection () {
      return this.tableInfo.selection.length === 0;
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      const actionList = [
        { label: '编辑', method: this.handleEdit, hasAuth: true },
        { label: '删除', method: this.handleDelete, hasAuth: true },
        { label: '查看', method: this.handleView, hasAuth: false },
      ];
      return getTableAction({ h, row, actionList, showBtn: this.showBtn });
    },
    // 在mounted时期加载初始数据
    loadInitDataInMounted () {
      this.handleQueryForm();
    },
    // 获取表单内容
    getFormData (data) {
      this.formData = data;
    },
    // 获取查询入参
    getParamsBySearch () {
      const getTime = (key, times) => {
        if (!times) {
          return {
            [`${key}Start`]: '',
            [`${key}End`]: ''
          }
        }
        return {
          [`${key}Start`]: times[0] || '',
          [`${key}End`]: times[1] || '',
        }
      }
      const { nowPage, pageShow } = this.pagination;
      const {
        qualificationName, supplyName, supplyNo,
        supplierManageAreaName, purchaseAttributionName,
        createOpeTime, opeTime, expireDateStart, expireDateEnd, supplierStatusName
      } = this.formData;
      return {
        qualificationName,
        supplyName,
        supplyNo,
        supplierManageAreaName,
        purchaseAttributionName,
        ...getTime('createOpeTime', createOpeTime),
        ...getTime('opeTime', opeTime),
        expireDateStart,
        expireDateEnd,
        supplierStatusName,
        nowPage,
        pageShow
      }
    },
    // 获取表格数据 by 查询表单
    async getTableDataBySearchForm () {
      sessionStorage.setItem('buttonId', getBtnsId('查询'));
      const retData = await requestToData({
        url: '/sysback/qualification/getQuaHomePager',
        type: 'post',
        data: this.getParamsBySearch(),
      }, () => { this.tableInfo.loading = true },
      () => { this.tableInfo.loading = false });
      if (retData) {
        this.tableInfo.list = retData?.results || [];
        this.pagination.totalNum = retData?.totalNum || 0;
      }
    },
    // 表单查询
    handleQueryForm () {
      this.pagination.nowPage = 1;
      this.getTableDataBySearchForm();
    },
    // 页码切换
    handlePageChange (val) {
      this.pagination.nowPage = val;
      this.getTableDataBySearchForm();
    },
    // 每页条数切换
    handlePageSizeChange (val) {
      this.pagination.pageShow = val;
      this.getTableDataBySearchForm();
    },
    // 表格勾选
    handleTableSelection (list) {
      this.tableInfo.selection = list;
    },
    // 新增
    handleAdd () {
      this.$router.push({ name: 'qualificationsManageAdd' });
    },
    // 导出
    handleExport () {
      const data = this.getParamsBySearch();
      this.exportQuaInfo(data);
    },
    // 编辑
    handleEdit (row) {
      this.qualificationEdit.uuid = row.uuid;
      this.qualificationEdit.visible = true;
      this.qualificationEdit.isView = false;
    },
    // 删除
    handleDelete (row) {
      this.deleteQuaInfo({ quaUuids: [row.uuid] },
        '删除成功',
        () => { this.tableInfo.loading = true; },
        () => { this.tableInfo.loading = false; }
      );
    },
    // 查看
    handleView (row) {
      this.qualificationEdit.uuid = row.uuid;
      this.qualificationEdit.visible = true;
      this.qualificationEdit.isView = true;
    },
    // 批量删除
    handleBatchDelete () {
      this.deleteQuaInfo({ quaUuids: getListByReturnMapKey(this.tableInfo.selection) },
        '批量删除成功',
        () => { this.btnLoading.delete = true; },
        () => { this.btnLoading.delete = false; }
      );
    },
    // 删除操作
    deleteQuaInfo (data, successMsg, openLoding, closeLoading) {
      this.$confirm(
        '你确定要批量删除资质吗？',
        { title: '删除', type: 'warning' }
      ).then(async () => {
        const retStatus = await requestToStatus({
          url: '/sysback/qualification/deleteQuaInfoList',
          type: 'post',
          data,
        }, () => { openLoding(); },
        () => { closeLoading(); });
        if (retStatus) {
          this.$message.success(successMsg);
          this.getTableDataBySearchForm();
        }
      }).catch(() => {});
    },
    // 导出资质信息
    async exportQuaInfo (data) {
      const res = await requestToExport({
        url: '/sysback/qualification/exportQuaInfo',
        type: 'post',
        data
      }, () => { this.btnLoading.export = true; }, () => { this.btnLoading.export = false; });
      createExcelByExport({ excelTitle: '资质附件', res });
    }
  }
}
</script>
